package com.example.spring2013android;

import java.util.ArrayList;
import java.util.List;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity
{
	private TextView mHeaderTextView;
	
	private Button mButtonOne;

	private int mCounter;
	
	private List<Contact> mListofcontacts = new ArrayList<Contact>();
	
	private static final String TAG = "MainActivity";
	
	protected class BackgroundTask extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPostExecute(Void result) {
			// TODO Here we shall ring an alarm sound

			doNext();
		}

		@Override
		protected void onPreExecute() {
			// reset counter
			mCounter = 0;
		}

		@Override
		protected void onProgressUpdate(Void... values) {
			mHeaderTextView.setText(String.valueOf(mCounter));
			Log.d(TAG,
					"The value of mCounter is" + String.valueOf(mCounter));
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			while (mCounter < 2) {
				mCounter++;
				this.publishProgress(params);
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					Log.e(TAG, e.toString());
				}
			}
			
			ObjectsReader reader = new ObjectsReader();
			
			mListofcontacts = reader.readPersons(Configuration.CONTACTS_URL);
			return null;
		}

	}
	public void doNext()
	{
		for (Contact c : mListofcontacts)
		{
			Log.d(TAG, "-----------------" + c.getName() + "---" + c.getAge());
		}
	}
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		mHeaderTextView = (TextView) findViewById(R.id.headerTextView);
		
		mButtonOne = (Button) findViewById(R.id.buttonOne);
		
		mButtonOne.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				mHeaderTextView.setText("Button was clicked");
				Log.d(TAG,
						"Start counter");
				new BackgroundTask().execute();
				
			}
		});
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
